import 'dart:math';

import 'package:async/async.dart';
import 'package:bai_le_men_im/cmomon/utils.dart';
import 'package:bai_le_men_im/constants.dart';
import 'package:bai_le_men_im/conversation/groupMessagesPage.dart';
import 'package:bai_le_men_im/conversation/messagesPage.dart';
import 'package:bai_le_men_im/models/index.dart';
import 'package:bai_le_men_im/pages/search/matchKeywordForTarget.dart';
import 'package:bai_le_men_im/pages/search/searchAppBar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wildfire/flutter_wildfire.dart';
import '../../constants.dart' show AppColors;
import 'package:intl/intl.dart';
import 'package:flutter/foundation.dart';

class SearchKeywordInAll extends StatefulWidget {
  @override
  _SearchKeywordInAllState createState() => _SearchKeywordInAllState();
}

class _SearchKeywordInAllState extends State<SearchKeywordInAll> {
  String target;
  String targetType;
  String _keyword = '';
  bool _showResults = false;
  List<Map<dynamic, dynamic>> searchResult = new List<Map<dynamic, dynamic>>();
  List<User> users = new List<User>();
  List<Group> groups = new List<Group>();
  List<Map> conversations = new List<Map>();

  /// 用来保存目标(用户或者群组)的详情
  List<dynamic> targets = new List<dynamic>();

  @override
  void initState() {
    super.initState();
  }

  updateTarget(dynamic target) {
    if (!(target is User) && !(target is Group)) return;
    int index = targets.indexWhere((dynamic item) {
      if (target is User) {
        if (item is User) {
          if (target.uid == item.uid) {
            return true;
          }
        }
      } else if (target is Group) {
        if (item is Group) {
          if (target.target == item.target) {
            return true;
          }
        }
      }
      return false;
    });
    if (index > -1) {
      return;
    } else {
      targets.add(target);
    }
  }

  keywordControllerChangedHandler(String keyword) async {
    this.setState(() {
      _keyword = keyword;
      _showResults = false;
    });
  }

  searchUsers(String keyword) async {
    var result = await FlutterWildfire.searchUser(keyword, true);
    List<User> users = new List<User>();
    users.clear();
    for (var item in result) {
      User user = User.fromJson(item);
      users.add(user);
      updateTarget(user);
    }

    return users;
  }

  searchGroups(String keyword) async {
    var fechResult = await FlutterWildfire.searchGroups(keyword);
    List<Group> results = new List<Group>();
    for (var item in fechResult) {
      // TODO: marchedMembers 和 marchedType 字段
      Group group = Group.fromJson(item['groupInfo']);
      results.add(group);
      updateTarget(group);
    }
    return results;
  }

  searchMessages(String keyword) async {
    var fechResult = await FlutterWildfire.searchConversation(
        ['Single', 'Group'], [0], keyword);
    List<Map> results = new List<Map>();
    results.clear();
    for (var item in fechResult) {
      results.add(item);
    }
    return results;
  }

  search() async {
    final keyword = _keyword;
    users.clear();
    users.addAll(await searchUsers(keyword));
    groups.clear();
    groups.addAll(await searchGroups(keyword));
    conversations.clear();
    conversations.addAll(await searchMessages(keyword));
    setState(() {
      _showResults = true;
    });
    return;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromRGBO(237, 237, 237, 1.0),
      appBar: SearchAppBar(
          onkeywordControllerChangedHandler: keywordControllerChangedHandler),
      body: Container(
        child: Column(
          children: <Widget>[
            Expanded(
              child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onPanDown: (_) {
                    FocusScope.of(context).requestFocus(FocusNode());
                  },
                  child: _keyword.isEmpty
                      ? EmptyKeyWord()
                      : (_showResults == false
                          ? Container(
                              decoration: BoxDecoration(
                                  border: Border(
                                      bottom:
                                          BorderSide(color: Colors.grey[300]))),
                              child: ListTile(
                                onTap: search,
                                title: Text(
                                  '搜索:"$_keyword"',
                                  style: TextStyle(color: Colors.blueAccent),
                                ),
                              ),
                            )
                          : renderResult())),
            )
          ],
        ),
      ),
    );
  }

  Widget renderUser(List<User> _users) {
    if (_users == null || _users.length == 0) {
      return Container();
    }
    return Container(
      color: Colors.white,
      margin: const EdgeInsets.only(bottom: 10.0),
      child: Padding(
        padding: const EdgeInsets.only(left: 12.0),
        child: Column(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.symmetric(vertical: 10.0),
              alignment: Alignment(-1, 0),
              child: Text('联系人'),
            ),
            Divider(
              height: 0.0,
            ),
            ..._users
                // .sublist(0, _users.length <= 3 ? _users.length : 3)
                .map((User user) {
              return Stack(
                children: <Widget>[
                  InkWell(
                    onTap: () async {
                      await Navigator.of(context)
                          .push(new MaterialPageRoute(builder: (context) {
                        return MessagesPage(user: user);
                      }));
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(vertical: 10.0),
                      child: Row(
                        children: <Widget>[
                          ClipRRect(
                              borderRadius:
                                  BorderRadius.circular(Constants.AvatarRadius),
                              child: myAvatar(user.portrait)),
                          const SizedBox(
                            width: 12.0,
                          ),
                          Expanded(
                            child: colorKeyWord(user.friendAlias != null &&
                                    user.friendAlias != ''
                                ? user.friendAlias
                                : user.displayName),
                          )
                        ],
                      ),
                    ),
                  ),
                  Positioned(
                    left: 60.0,
                    bottom: 0.0,
                    right: 0.0,
                    child: Container(
                      height: 0.5,
                      color: Colors.grey[200],
                    ),
                  )
                ],
              );
            }).toList(),
            // _users.length > 3
            //     ? Container(
            //         padding: const EdgeInsets.symmetric(vertical: 10.0),
            //         child: Row(
            //           children: <Widget>[
            //             const Icon(
            //               Icons.search,
            //               color: Color.fromRGBO(97, 103, 139, 1),
            //               size: 18.0,
            //             ),
            //             const SizedBox(
            //               width: 5.0,
            //             ),
            //             const Expanded(
            //               child: Text(
            //                 '更多联系人',
            //                 style: TextStyle(
            //                     fontSize: 14.0,
            //                     color: Color.fromRGBO(97, 103, 139, 1)),
            //               ),
            //             ),
            //             const Icon(
            //               Icons.chevron_right,
            //               color: Color.fromRGBO(97, 103, 139, 1),
            //               size: 18.0,
            //             )
            //           ],
            //         ),
            //       )
            //     : Container()
          ],
        ),
      ),
    );
  }

  Widget renderGroups(List<Group> _group) {
    if (_group == null || _group.length == 0) {
      return Container();
    }

    return Container(
      color: Colors.white,
      margin: const EdgeInsets.only(bottom: 10.0),
      child: Padding(
        padding: const EdgeInsets.only(left: 12.0),
        child: Column(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.symmetric(vertical: 10.0),
              alignment: Alignment(-1, 0),
              child: Text('群聊'),
            ),
            Divider(
              height: 0.0,
            ),
            ..._group
                // .sublist(0, _group.length <= 3 ? _group.length : 3)
                .map((Group group) {
              return Stack(
                children: <Widget>[
                  InkWell(
                    onTap: () async {
                      await Navigator.of(context)
                          .push(new MaterialPageRoute(builder: (context) {
                        return GroupMessagesPage(groupInfo: group);
                      }));
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(vertical: 10.0),
                      child: Row(
                        children: <Widget>[
                          ClipRRect(
                              borderRadius:
                                  BorderRadius.circular(Constants.AvatarRadius),
                              child: myAvatar(group.portrait)),
                          const SizedBox(
                            width: 12.0,
                          ),
                          Expanded(
                            child: Text(
                              (group.name != null ? group.name : '') +
                                  '(${group.memberCount})',
                              style: TextStyle(
                                fontSize: 18.0,
                              ),
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Positioned(
                    left: 60.0,
                    bottom: 0.0,
                    right: 0.0,
                    child: Container(
                      height: 0.5,
                      color: Colors.grey[200],
                    ),
                  )
                ],
              );
            }).toList(),
            // _group.length > 3
            //     ? Container(
            //         padding: const EdgeInsets.symmetric(vertical: 10.0),
            //         child: Row(
            //           children: <Widget>[
            //             const Icon(
            //               Icons.search,
            //               color: Color.fromRGBO(97, 103, 139, 1),
            //               size: 18.0,
            //             ),
            //             const SizedBox(
            //               width: 5.0,
            //             ),
            //             const Expanded(
            //               child: Text(
            //                 '更多群聊',
            //                 style: TextStyle(
            //                     fontSize: 14.0,
            //                     color: Color.fromRGBO(97, 103, 139, 1)),
            //               ),
            //             ),
            //             const Icon(
            //               Icons.chevron_right,
            //               color: Color.fromRGBO(97, 103, 139, 1),
            //               size: 18.0,
            //             )
            //           ],
            //         ),
            //       )
            //     : Container()
          ],
        ),
      ),
    );
  }

  Widget renderConversations(List<Map> _arr) {
    String _strTypeChn = '聊天记录';
    if (_arr == null || _arr.length == 0) {
      return Container();
    }

    return Container(
      color: Colors.white,
      margin: const EdgeInsets.only(bottom: 10.0),
      child: Padding(
        padding: const EdgeInsets.only(left: 12.0),
        child: Column(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.symmetric(vertical: 10.0),
              alignment: Alignment(-1, 0),
              child: Text(_strTypeChn),
            ),
            Divider(
              height: 0.0,
            ),
            ..._arr
                // .sublist(0, _arr.length <= 3 ? _arr.length : 3)
                .map((Map item) {
              String type = item['conversation']['type'];
              int index = targets.indexWhere((dynamic targetObj) {
                if (type == 'Group') {
                  if (targetObj is User) return false;
                  return targetObj.target == item['conversation']['target'];
                } else if (type == 'Single') {
                  if (targetObj is Group) return false;
                  return targetObj.uid == item['conversation']['target'];
                }
                return false;
              });
              var targetObj;
              if (index > -1) {
                targetObj = targets[index];
              }
              return Stack(
                children: <Widget>[
                  TargetConversation(
                      colorKeyWord: colorKeyWord,
                      targetObj: targetObj,
                      type: item['conversation']['type'],
                      targetId: item['conversation']['target'],
                      marchedCount: item['marchedCount'],
                      keyword: this._keyword,
                      marchedMessage: item['marchedMessage'],
                      updateTarget: updateTarget),
                  Positioned(
                    left: 60.0,
                    bottom: 0.0,
                    right: 0.0,
                    child: Container(
                      height: 0.5,
                      color: Colors.grey[200],
                    ),
                  )
                ],
              );
            }).toList(),
            // _arr.length > 3
            //     ? Container(
            //         padding: const EdgeInsets.symmetric(vertical: 10.0),
            //         child: Row(
            //           children: <Widget>[
            //             const Icon(
            //               Icons.search,
            //               color: Color.fromRGBO(97, 103, 139, 1),
            //               size: 18.0,
            //             ),
            //             const SizedBox(
            //               width: 5.0,
            //             ),
            //             Expanded(
            //               child: Text(
            //                 '更多$_strTypeChn',
            //                 style: TextStyle(
            //                     fontSize: 14.0,
            //                     color: Color.fromRGBO(97, 103, 139, 1)),
            //               ),
            //             ),
            //             const Icon(
            //               Icons.chevron_right,
            //               color: Color.fromRGBO(97, 103, 139, 1),
            //               size: 18.0,
            //             )
            //           ],
            //         ),
            //       )
            //     : Container()
          ],
        ),
      ),
    );
  }

  Widget renderResult() {
    bool _hasResult =
        users.length > 0 || groups.length > 0 || conversations.length > 0;
    if (_hasResult == false) {
      return Container(
        padding: EdgeInsets.only(top: 30.0),
        child: Column(
          children: <Widget>[
            Center(
              child: Text.rich(
                TextSpan(children: [
                  TextSpan(text: '没有找到"', style: TextStyle(color: Colors.grey)),
                  TextSpan(
                      text: this._keyword,
                      style: TextStyle(
                          color: const Color(AppColors.TabIconActive))),
                  TextSpan(text: '"相关记录', style: TextStyle(color: Colors.grey))
                ], style: TextStyle(fontSize: 17.0)),
              ),
            )
          ],
        ),
      );
    }

    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          renderUser(users),
          renderGroups(groups),
          renderConversations(conversations)
        ],
      ),
    );
    
  }

  Widget colorKeyWord(String content) {
    String _keyword = this._keyword;
    List<String> _arrOthers = content.split(_keyword);
    List<TextSpan> _finalArr = new List<TextSpan>();
    for (int i = 0; i < _arrOthers.length; i++) {
      _finalArr.add(TextSpan(
          text: _arrOthers[i], style: TextStyle(color: Colors.black87)));
      if (i != _arrOthers.length - 1) {
        _finalArr.add(TextSpan(
            text: _keyword,
            style: TextStyle(color: const Color(AppColors.TabIconActive))));
      }
    }

    return Text.rich(
      TextSpan(children: [..._finalArr], style: TextStyle(fontSize: 16.0)),
      overflow: TextOverflow.ellipsis,
      maxLines: 1,
    );
  }
}

class EmptyKeyWord extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.only(top: 15.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '输入关键词搜索',
            style: TextStyle(color: Color.fromRGBO(97, 103, 139, 1)),
          )
        ],
      ),
    );
  }
}

class TargetConversation extends StatefulWidget {
  final int marchedCount;
  final dynamic targetObj;
  final String targetId;
  final String type;
  final Function updateTarget;
  final Function colorKeyWord;
  final String keyword;
  final Map marchedMessage;
  TargetConversation(
      {this.targetObj,
      this.marchedCount,
      this.updateTarget,
      this.colorKeyWord,
      this.targetId,
      @required this.keyword,
      this.marchedMessage,
      this.type});
  @override
  _TargetConversationState createState() => _TargetConversationState();
}

class _TargetConversationState extends State<TargetConversation> {
  final AsyncMemoizer _memoizer = AsyncMemoizer();
  getTarget() {
    return _memoizer.runOnce(() async {
      var targetObj = widget.targetObj;
      if (targetObj != null) {
        return targetObj;
      }
      if (widget.type == 'Group') {
        Group group =
            Group.fromJson(await FlutterWildfire.getGroupInfo(widget.targetId));
        widget.updateTarget(group);
        return group;
      }

      if (widget.type == 'Single') {
        User user = User.fromJson(
            await FlutterWildfire.getUserInfo(widget.targetId, true));
        widget.updateTarget(user);
        return user;
      }
    });
  }

  Widget renderSingleMessage(dynamic marchedMessage) {
    if (marchedMessage['content'] != null) {
      if (marchedMessage['content']['content'] != null &&
          (marchedMessage['content']['content'] is String)) {
        return Container(
          child: widget.colorKeyWord(marchedMessage['content']['content']),
        );
      }
      // TODO: 红包消息没有处理
    }
    return Container();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: getTarget(),
        builder: (context, snapshot) {
          var targetObj;
          var _avatar = '';
          var _displayName = '';
          if (snapshot.hasData) {
            targetObj = snapshot.data;
          } else {
            targetObj = widget.targetObj;
          }
          if (targetObj != null) {
            _avatar = targetObj.portrait;
            if (targetObj is User) {
              if (targetObj.friendAlias != null &&
                  targetObj.friendAlias != '') {
                _displayName = targetObj.friendAlias;
              } else {
                _displayName = targetObj.displayName;
              }
            } else if (targetObj is Group) {
              _displayName = targetObj.name;
            }
          }

          return InkWell(
            onTap: () async {
              await Navigator.of(context)
                  .push(new MaterialPageRoute(builder: (context) {
                if (widget.marchedMessage != null) {
                  Widget _pageWidget;
                  if (widget.type == 'Single') {
                    _pageWidget = MessagesPage(
                        user: widget.targetObj,
                        messageId: widget.marchedMessage['messageId']);
                  } else {
                    _pageWidget = GroupMessagesPage(
                        groupInfo: widget.targetObj,
                        messageId: widget.marchedMessage['messageId']);
                  }
                  return _pageWidget;
                } else {
                  return MatchKeywordForTarget(
                    displayName: _displayName,
                    targetObj: targetObj,
                    keyword: widget.keyword,
                  );
                }
              }));
            },
            child: Container(
              padding: const EdgeInsets.symmetric(vertical: 10.0),
              child: Row(
                children: <Widget>[
                  ClipRRect(
                      borderRadius:
                          BorderRadius.circular(Constants.AvatarRadius),
                      child: myAvatar(_avatar)),
                  const SizedBox(
                    width: 12.0,
                  ),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          _displayName,
                          style: TextStyle(
                            fontSize: 16.0,
                          ),
                        ),
                        widget.marchedMessage != null
                            ? renderSingleMessage(widget.marchedMessage)
                            : (Text(
                                '${widget.marchedCount}条相关聊天记录',
                                style: TextStyle(
                                    fontSize: 14.0, color: Colors.grey),
                                overflow: TextOverflow.ellipsis,
                              ))
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
        });
  }
}
